package com.iscas.dataaggregation.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.api.model.ServiceList;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class ServicesUtils {

    private static final Logger logger = Logger.getLogger(ServicesUtils.class);

    @Autowired
    private KubernetesClient kubernetesClient;
    /**
     * 根据 namespace 获取服务名称列表
     *
     * @param namespace 指定的命名空间
     * @return 匹配命名空间的 ServiceName 列表
     */
    public List<String> getServiceNamesByNamespace(String namespace) {
        List<String> serviceNames = new ArrayList<>();
        String url = "http://60.245.215.207:30080/api/project/pqnv7ole/overview/health";

        logger.info("Starting to fetch service names for namespace: " + namespace);

        try {
            // 使用 RestTemplate 发送 GET 请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            // 获取响应 Body
            String body = response.getBody();
            logger.debug("Response body received: " + body);

            // 解析 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(body);
            logger.info("JSON response successfully parsed.");

            // 查找 context.search.applications 节点
            JsonNode applicationsNode = rootNode.path("context").path("search").path("applications");

            if (applicationsNode.isMissingNode()) {
                logger.warn("Node 'context.search.applications' is missing in the response.");
                return serviceNames;
            }

            // 遍历 applications，提取 serviceName
            if (applicationsNode.isArray()) {
                logger.info("Iterating over applications to extract service names...");
                for (JsonNode application : applicationsNode) {
                    // 提取 id 节点
                    String fullServiceName = application.path("id").asText();
                    logger.debug("Processing service id: " + fullServiceName);

                    // 匹配格式并判断 namespace 是否匹配
                    if (fullServiceName.contains(":Deployment:") && fullServiceName.startsWith(namespace + ":")) {
                        String[] parts = fullServiceName.split(":");
                        if (parts.length == 3) {
                            String serviceName = parts[2];
                            logger.info("Service matched for namespace '" + namespace + "': " + serviceName);
                            serviceNames.add(serviceName); // 提取 serviceName
                        } else {
                            logger.warn("Unexpected service id format: " + fullServiceName);
                        }
                    } else {
                        logger.debug("Skipping service id as it does not match namespace: " + fullServiceName);
                    }
                }
            } else {
                logger.warn("Expected an array under 'context.search.applications', but found: " + applicationsNode);
            }
        } catch (Exception e) {
            logger.error("Error occurred while fetching or parsing data from URL: " + url, e);
        }

        logger.info("Service name extraction completed. Total services found: " + serviceNames.size());
        return serviceNames;
    }

    /**
     * 根据命名空间和选择器定位到服务名称
     *
     * @param namespace 命名空间
     * @param selector  选择器 (如 {"app": "ts-travel-service"})
     * @return 匹配的服务名称列表
     */
    public List<String> getServiceNamesByNamespaceAndSelector(String namespace, Map<String, String> selector) {
        logger.info("Fetching services in namespace: " + namespace + " with selector: " + selector);
        List<String> matchedServiceNames = new ArrayList<>();

        try {
            // 查询命名空间中的所有服务
            ServiceList serviceList = kubernetesClient.services().inNamespace(namespace).list();

            if (serviceList == null || serviceList.getItems().isEmpty()) {
                logger.warn("No services found in namespace: " + namespace);
                return matchedServiceNames;
            }

            // 遍历服务，匹配 selector
            logger.info("Filtering services based on selector...");
            serviceList.getItems().forEach(service -> {
                Map<String, String> serviceSelector = service.getSpec().getSelector();
                if (selector.equals(serviceSelector)) {
                    String serviceName = service.getMetadata().getName();
                    matchedServiceNames.add(serviceName);
                    logger.info("Matched Service Name: " + serviceName);
                }
            });
        } catch (Exception e) {
            logger.error("Error fetching services for namespace: " + namespace, e);
        }

        logger.info("Matched services count: " + matchedServiceNames.size());
        return matchedServiceNames;
    }

}